<?php
/**
 * Created by PhpStorm.
 * User: lh_or
 * Date: 2018/8/13
 * Time: 15:24
 */
namespace Api\Controller;
/*
 * 退款控制器
 * */
//require VENDOR_PATH.'Refund/AlipayTradeRefundContentBuilder.php';
//require VENDOR_PATH.'Refund/AlipayTradeService.php';
vendor('Refund.AlipayTradeRefundContentBuilder');
vendor('Refund.AlipayTradeService');

class RefundController extends BaseController
{
    /* 退款 */
    public function payback(){
        $id = trim(I('post.id',''));
        $where = [
            'refund_id' => $id,
            'refund_type' => 1, //类型为退款
            'shop_state' => 2, //处理状态为同意
            'refund_state' => 1, //申请状态为处理中
            'settlement_status' => 1 //结算状态为已结算
        ];
        /* 获取订单支付状态、物流信息 */
        $refundInfo = M('order_refund')
            -> field('order_sn,reason,amount,goods_name,goods_id,refund_sn')
            -> where($where)
            -> find();
        if(!$refundInfo){
            exit(json_encode(['result' => 400,'message' => '暂不满足退款条件，请联系开发人员']));
        }

        try{
            $RefundLogic = new \Common\Logic\RefundLogic;
            $result = $RefundLogic -> refundByRefundSn($refundInfo['refund_sn']);
        }catch(\Exception $e)
        {
            exit(json_encode(['result' => $e->getCode(),'message' => $e->getMessage()]));
        }
        
     
        if($result)
        {
            exit(json_encode(['result' => 200,'message' => '退款成功']));
        }else{
            /* 退款失败 */
            exit(json_encode(['result' => 402,'message' => '退款失败，请联系开发人员,查询退款记录']));
        }
    }

    /* 取消申请 */
    public function cancel(){
        $id = trim(I('post.id',''));
        if(empty($id)){
            exit(json_encode(['result' => 400,'message' => '获取id失败']));
        }
        $data['refund_id'] = $id;
        $data['shop_state'] = 0;
        $data['refund_state '] = 0;
        $data['status '] = 0;
        $orderRefund = M('order_refund');
        $saveId = $orderRefund -> save($data);
        if($saveId){
            exit(json_encode(['result' => 200,'message' => '取消申请成功']));
        }else{
            exit(json_encode(['result' => 401,'message' => '取消申请失败']));
        }
    }

    /* 申请退款 */
    public function apply(){
        if (!$this->user_id) {
           $this->returnInfo('-1','缺少参数');
        }
        $data['order_sn'] = trim(I('post.order_sn',''));
        $data['goods_id'] = trim(I('post.goods_id',0));
        $data['cargo_state'] = trim(I('post.cargo_state',''));
        $data['reason'] = trim(I('post.reason',''));
        $data['amount'] = trim(I('post.amount',''));
        $data['description'] = trim(I('post.description',''));
        if(IS_POST){
            // 晒图片
            if($_FILES)
            {
                $upload = new \Think\Upload();// 实例化上传类
                $upload->maxSize   =    $map['author'] = (1024*1024*3);// 设置附件上传大小 管理员10M  否则 3M
                $upload->exts      =    array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->rootPath  =    './Public/upload/return_goods/'; // 设置附件上传根目录
                $upload->replace   =    true; // 存在同名文件是否是覆盖，默认为false
                //$upload->saveName  =  'file_'.$id; // 存在同名文件是否是覆盖，默认为false
                // 上传文件
                $upinfo  =  $upload->upload();
                if(!$upinfo) {// 上传错误提示错误信息
                    $this->error($upload->getError());
                }else{
                    foreach($upinfo as $key => $val)
                    {
                        $return_imgs[] = $val['urlpath'];
                    }
                    $data['images'][] = implode(',', $return_imgs);// 上传的图片文件
                }
            } 
        /* 验证 */
        $validateMsg = $this -> validate($data);
        if($validateMsg){
            exit(json_encode(['result' => 401,'message' => $validateMsg]));
        }
        /* 获取用户信息 */
        $this -> getUserInfo($data);

        /* 获取商品信息 */
        $this -> getProductInfo($data);
        $data['refund_type'] = 1;
        $data['shop_state'] = 1;
        $data['refund_state'] = 1;
        $data['status'] = 1;
        $data['add_time'] = time();
        $data['amount'] = $this -> multiply100($data['amount']);
        $orderRefund = M('order_refund');
        $insert_id = $orderRefund -> add($data);
        if($insert_id){
            exit(json_encode(['result' => 1,'message' => '退款申请提交成功']));
        }else{
            exit(json_encode(['result' => -1,'message' => '退款申请提交失败']));
        }
    }
}

    /* 商品信息 */
    public function getProductInfo(&$data){
        /* 获取订单支付状态、物流信息 */
        $orderInfo = M('order')
                    -> field('order_id,shipping_code,shipping_name,pay_status')
                    -> where("`order_sn` = ".$data['order_sn'])
                    -> find();
        $data['express_name'] = $orderInfo['shipping_name'];
        $data['express_code'] = $orderInfo['shipping_code'];
        $data['settlement_status'] = $orderInfo['pay_status'];
        if(!$orderInfo){
            exit(json_encode(['result' => 403,'message' => '获取订单信息失败']));
        }
        if( $orderInfo['is_groupbuy'] == 2 )
        {
            return $this->returnInfo(-1, '兑换订单不支持退款');
        }
        /* 判断是否需要全部退款 */
        if($data['goods_id'] == 0){
            /* 商品名称、购买数量 */
            $productInfo = M('order_goods')
                        -> field('goods_name,goods_num')
                        -> where('`order_id` = '.$orderInfo['order_id'])
                        -> select();
            $data['goods_name'] = [];
            if(!$productInfo){
                exit(json_encode(['result' => 404,'message' => '获取订单商品信息失败']));
            }
            foreach ($productInfo as $k => $v){
                array_push($data['goods_name'],$v['goods_name']);
                $data['goods_num'] += $v['goods_num'];
            }
            $data['goods_name'] = implode(',',$data['goods_name']);
            $data['order_goods_id'] = 0;
        }else{
            /* 商品名称、购买数量 */
            $productInfo = M('order_goods')
                        -> field('rec_id as id,goods_name,goods_num')
                        -> where(['order_id' =>$orderInfo['order_id'] ,'goods_id' => ['in',explode(',',$data['goods_id'])]])
                        -> select();
            if(!$productInfo){
                exit(json_encode(['result' => 404,'message' => '获取订单商品信息失败']));
            }
            $data['goods_name'] = [];
            $data['order_goods_id'] = [];
            foreach ($productInfo as $k => $v){
                array_push($data['goods_name'],$v['goods_name']);
                array_push($data['order_goods_id'],$v['id']);
                $data['goods_num'] += $v['goods_num'];
            }
            $data['goods_name'] = implode(',',$data['goods_name']);
            $data['order_goods_id'] = implode(',',$data['order_goods_id']);
            $data['refund_sn'] = 'RF'.time().rand(10,100);
        }
    }

    /* 用户信息 */
    public function getUserInfo(&$data){
        /* 用户昵称 */
        $userInfo = M('users') -> field('nickname') -> where("`user_id` = ".$data['user_id']) -> find();
        $data['user_name'] = $userInfo['nickname'];
    }

    /* 数据验证 */
    public function validate($data){
        $info[] = $data;
        $str = '';
        foreach ($info as $k => $v){
            if(empty($v['user_id'])){
                $str = '用户id不能为空';
            }
            if(empty($v['order_sn'])){
                $str = '订单编号不能为空';
            }
            if(empty($v['cargo_state'])){
                $str = '货物状态不能为空';
            }
            if(empty($v['reason'])){
                $str = '退款原因不能为空';
            }
            if(empty($v['amount'])){
                $str = '退款金额不能为空';
            }
            if(empty($v['description'])){
                $str = '退款说明不能为空';
            }
            if(empty($v['images'])){
                $str = '退款凭证不能为空';
            }
        }
        return $str;
    }

    //把所有金额乘以100，保持金额为整数，单位为分
    public function multiply100($in){
        $in = "$in";
        if(false === strpos($in,".")){
            return intval($in)*100;
        }else{
            $arr = explode(".",$in);
            if($arr[0] == ""){
                $arr[0]=0;
            }
            $in = $arr[0].".".$arr[1]."00";
            $pos = strpos($in,".");
            $ret = substr($in,0,$pos).substr($in,$pos+1,2);
            return intval($ret);
        }
    }

    //把所有的金额 除以100
    public function divide100($in){
        if (empty($in)) {
            return "0.00";
        }else{
            $res = intval($in)/100;
            return $res;
        }
    }

}